import 'package:flutter/material.dart';
import '../data/models/destination_model.dart';
import '../services/destination_service.dart';

class DestinationProvider extends ChangeNotifier {
  final DestinationService _destinationService = DestinationService();

  // 状态变量
  List<Destination> _destinations = [];
  bool _isLoading = false;
  String? _errorMessage;

  // 分页相关
  int _currentPage = 1;
  int _totalPages = 1;
  int _totalCount = 0;
  final int _pageSize = 6; // 每页显示6个目的地

  // 筛选和排序
  DestinationSortOption _currentSort = DestinationSortOption.popular;
  DestinationCategory _currentCategory = DestinationCategory.all;
  String _searchQuery = '';

  // Getters
  List<Destination> get destinations => _destinations;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;
  int get currentPage => _currentPage;
  int get totalPages => _totalPages;
  int get totalCount => _totalCount;
  int get pageSize => _pageSize;
  DestinationSortOption get currentSort => _currentSort;
  DestinationCategory get currentCategory => _currentCategory;
  String get searchQuery => _searchQuery;

  // 是否有更多页面
  bool get hasNextPage => _currentPage < _totalPages;
  bool get hasPreviousPage => _currentPage > 1;

  // 初始化加载
  Future<void> initialize() async {
    await loadDestinations(refresh: true);
  }

  // 加载目的地列表
  Future<void> loadDestinations({bool refresh = false}) async {
    if (refresh) {
      _currentPage = 1;
      _destinations.clear();
    }

    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final response = await _destinationService.getDestinations(
        page: _currentPage,
        pageSize: _pageSize,
        sortBy: _currentSort.value,
        category: _currentCategory.value,
        search: _searchQuery.isNotEmpty ? _searchQuery : null,
      );

      if (refresh) {
        _destinations = response.destinations;
      } else {
        _destinations.addAll(response.destinations);
      }

      _totalPages = response.totalPages;
      _totalCount = response.totalCount;

      print('📍 加载了 ${response.destinations.length} 个目的地，总共 $_totalCount 个');
    } catch (e) {
      _errorMessage = '加载目的地失败: $e';
      print('❌ 加载目的地失败: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  // 跳转到指定页面
  Future<void> goToPage(int page) async {
    if (page < 1 || page > _totalPages || page == _currentPage) return;

    _currentPage = page;
    await loadDestinations(refresh: true);
  }

  // 下一页
  Future<void> nextPage() async {
    if (hasNextPage) {
      _currentPage++;
      await loadDestinations(refresh: true);
    }
  }

  // 上一页
  Future<void> previousPage() async {
    if (hasPreviousPage) {
      _currentPage--;
      await loadDestinations(refresh: true);
    }
  }

  // 更改排序方式
  Future<void> setSortOption(DestinationSortOption sortOption) async {
    if (_currentSort == sortOption) return;

    _currentSort = sortOption;
    await loadDestinations(refresh: true);
  }

  // 更改类别筛选
  Future<void> setCategoryFilter(DestinationCategory category) async {
    if (_currentCategory == category) return;

    _currentCategory = category;
    await loadDestinations(refresh: true);
  }

  // 更新搜索查询
  Future<void> updateSearchQuery(String query) async {
    if (_searchQuery == query) return;

    _searchQuery = query;
    await loadDestinations(refresh: true);
  }

  // 清除搜索
  Future<void> clearSearch() async {
    await updateSearchQuery('');
  }

  // 刷新数据
  Future<void> refresh() async {
    await loadDestinations(refresh: true);
  }

  // 清除错误信息
  void clearError() {
    _errorMessage = null;
    notifyListeners();
  }

  // 根据ID获取目的地详情
  Future<Destination?> getDestinationById(String id) async {
    try {
      // 先从已加载的列表中查找
      final existingDestination = _destinations.firstWhere(
        (dest) => dest.id == id,
        orElse: () => throw StateError('Not found'),
      );
      return existingDestination;
    } catch (e) {
      // 如果本地没有，从服务器获取
      try {
        return await _destinationService.getDestinationById(id);
      } catch (e) {
        print('❌ 获取目的地详情失败: $e');
        return null;
      }
    }
  }

  // 获取完整的目的地详情信息
  Future<DestinationDetail?> getDestinationDetail(String id) async {
    try {
      return await _destinationService.getDestinationDetail(id);
    } catch (e) {
      print('❌ 获取目的地详情失败: $e');
      return null;
    }
  }

  // 获取分页信息文本
  String getPaginationText() {
    if (_totalCount == 0) return '没有找到目的地';

    final start = (_currentPage - 1) * _pageSize + 1;
    final end =
        (_currentPage * _pageSize > _totalCount)
            ? _totalCount
            : _currentPage * _pageSize;

    return '显示 $start-$end 项，共 $_totalCount 项';
  }

  // 获取页码列表（用于分页器）
  List<int> getPageNumbers() {
    if (_totalPages <= 7) {
      return List.generate(_totalPages, (index) => index + 1);
    }

    List<int> pages = [];

    if (_currentPage <= 4) {
      pages.addAll([1, 2, 3, 4, 5]);
      pages.add(-1); // 省略号标记
      pages.add(_totalPages);
    } else if (_currentPage >= _totalPages - 3) {
      pages.add(1);
      pages.add(-1);
      for (int i = _totalPages - 4; i <= _totalPages; i++) {
        pages.add(i);
      }
    } else {
      pages.add(1);
      pages.add(-1);
      for (int i = _currentPage - 1; i <= _currentPage + 1; i++) {
        pages.add(i);
      }
      pages.add(-1);
      pages.add(_totalPages);
    }

    return pages;
  }
}
